package org.yaukie.auth.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.yaukie.auth.entity.LoginUser;
import org.yaukie.auth.service.api.TokenHandlerService;
import org.yaukie.base.util.StringTools;


@ConditionalOnProperty(prefix = "yaukie.auth", name = {"enabled"}, havingValue = "true")
@Component
public class JwtAuthenticationFilter
        extends OncePerRequestFilter {
    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class);


    @Autowired
    private TokenHandlerService tokenHandlerService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filter) throws ServletException, IOException {
        if (log.isInfoEnabled()) {
            log.info("系统模块{}执行令牌校验...", JwtAuthenticationFilter.class.getSimpleName());
        }
        boolean ifValidToken = this.tokenHandlerService.verifyToken(request);
        if (ifValidToken) {
            LoginUser loginUser = this.tokenHandlerService.getLoginUser(request);
            log.info("当前系统登录用户的token为{}", loginUser.getToken());
            if (StringTools.isNotNull(loginUser)) {
                UsernamePasswordAuthenticationToken upa = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                upa.setDetails((new WebAuthenticationDetailsSource()).buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(upa);
            }
        }
        filter.doFilter(request, response);
    }
}

